import {createStore} from 'vuex'
import {login, logout} from '@/api/user'
import {getInfo} from '@/api/user'
import {setToken, removeToken} from "@/utils/token";
import {resetRouter} from "@/router";

/**
 * 加载路由模块对象
 */

export const loadView = (view) => { // 路由懒加载
    // return import(`../views/${view}.vue`);
    const views = require.context('../views', true, /\.vue$/);
    return views(`./${view}.vue`).default;
    // return (resolve) => require([`../views/${view}.vue`], resolve)
    // return require(`${view}`).default
    // return () => Promise.resolve(require(`${view}`).default)
}
const menus2Routers = (menus) => {
    menus = menus.map(menu => {
        return {
            path: menu.resource_link,
            name: menu.resource_code,
            component: menu.resource_link,
            meta: {
                title: menu.resource_name,
                icon: menu.resource_icon,
                router_id: menu.resource_id,
                parent_id: menu.parent_id,
            }
        }
    })
    const newList = [];
    for (let i = 0; i < menus.length; i++) {
        if (menus[i].meta.parent_id === 0) {
            menus[i].component = () => import('@/components/Layout.vue')
            newList.push(menus[i]);
        } else {
            // 找到父类
            const findItem = menus.find((item) => item.meta.router_id === menus[i].meta.parent_id);
            if (findItem) {
                // 拼接路由
                menus[i].path = "" + findItem.path + menus[i].path
                // 找到模块位置
                menus[i].component = loadView(`${findItem.name}/${menus[i].name}`)
                // 父类是否存在 children 属性
                if (findItem.children) {
                    // 更改原数组就相当于给新数组里面添加了children，因为新数组里面元素的地址和原数组是一个、
                    findItem.children.push(menus[i]);
                } else {
                    findItem.children = [menus[i]];
                }
            }
        }
    }
    return newList;
}


export default createStore({
    modules: {},
    state: {
        page: {
            pageSizes: [10, 15, 20, 25],
            layout: 'total, sizes, prev, pager, next, jumper',
        },
        tagsList: [],
        collapse: false,
        user: null,
        token: null,
        roles: [],
        menus: [],
        routers: []
    },
    getters: {
        user: state => state.user,
        token: state => state.token,
        roles: state => state.roles,
        menus: state => state.menus,
        routers: state => state.routers,
    },
    mutations: {
        setToken: (state, token) => {
            state.token = token
        },
        setUser: (state, user) => {
            state.user = user
        },
        setRoles: (state, roles) => {
            state.roles = roles
        },
        setMenus: (state, menus) => {
            state.menus = menus
        },
        setRouters: (state, routers) => {
            state.routers = routers
        },
        delTagsItem(state, data) {
            state.tagsList.splice(data.index, 1);
        },
        setTagsItem(state, data) {
            state.tagsList.push(data)
        },
        clearTags(state) {
            state.tagsList = []
        },
        closeTagsOther(state, data) {
            state.tagsList = data;
        },
        closeCurrentTag(state, data) {
            for (let i = 0, len = state.tagsList.length; i < len; i++) {
                const item = state.tagsList[i];
                if (item.path === data.$route.fullPath) {
                    if (i < len - 1) {
                        data
                            .$router
                            .push(state.tagsList[i + 1].path);
                    } else if (i > 0) {
                        data
                            .$router
                            .push(state.tagsList[i - 1].path);
                    } else {
                        data
                            .$router
                            .push("/");
                    }
                    state
                        .tagsList
                        .splice(i, 1);
                    break;
                }
            }
        },
        // 侧边栏折叠
        hadndleCollapse(state, data) {
            state.collapse = data;
        }
    },
    actions: {
        // user login
        login({commit}, userInfo) {
            const {username, password} = userInfo
            return new Promise((resolve, reject) => {
                login({username: username.trim(), password: password}).then(response => {
                    const {data} = response
                    commit('setToken', data.token)
                    setToken(data.token)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // get user info
        getInfo({commit, state}) {
            return new Promise((resolve, reject) => {
                getInfo(state.token).then(response => {
                    const {data} = response
                    if (!data) {
                        reject('Verification failed, please Login again.')
                    }
                    // const { roles, name, avatar, introduction } = data
                    const {menus, roles, username, userId} = data

                    // roles must be a non-empty array
                    if (!roles || roles.length <= 0) {
                        reject('getInfo: roles must be a non-null array!')
                    }
                    const user = {username, userId}
                    const routers = menus2Routers(menus);
                    // console.log('菜单信息 ：',menus)
                    // console.log('路由信息 ：',routers)
                    commit('setRoles', roles)
                    commit('setUser', user)
                    commit('setMenus', menus)
                    commit('setRouters', routers)
                    resolve({user, roles, menus, routers})
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // user logout
        logout({commit, state, dispatch}) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    commit('setToken', '')
                    commit('setRoles', [])
                    commit('setMenus', [])
                    commit('routers', [])
                    removeToken()
                    resetRouter()

                    // reset visited views and cached views
                    // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
                    dispatch('tagsView/delAllViews', null, {root: true})

                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // remove token
        resetToken({commit}) {
            return new Promise(resolve => {
                commit('setToken', '')
                commit('setRoles', [])
                commit('setMenus', [])
                commit('routers', [])
                removeToken()
                resolve()
            })
        }
    }

})
